package com.zc.app.shiro.service;

import com.zc.app.shiro.dao.ResourceDao;
import com.zc.app.shiro.peer.ResourcePeer;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


//@Service
public class ResourceServiceImpl implements ResourceService {

//    @Autowired
    private ResourceDao resourceDao;

    @Override
    public ResourcePeer createResource(ResourcePeer resource) {
        return resourceDao.createResource(resource);
    }

    @Override
    public ResourcePeer updateResource(ResourcePeer resource) {
        return resourceDao.updateResource(resource);
    }

    @Override
    public void deleteResource(Long resourceId) {
        resourceDao.deleteResource(resourceId);
    }

    @Override
    public ResourcePeer findOne(Long resourceId) {
        return resourceDao.findOne(resourceId);
    }

    @Override
    public List<ResourcePeer> findAll() {
        return resourceDao.findAll();
    }

    @Override
    public Set<String> findPermissions(Set<Long> resourceIds) {
        Set<String> permissions = new HashSet<String>();
        for(Long resourceId : resourceIds) {
            ResourcePeer resource = findOne(resourceId);
            if(resource != null && !StringUtils.isEmpty(resource.getPermission())) {
                permissions.add(resource.getPermission());
            }
        }
        return permissions;
    }

    @Override
    public List<ResourcePeer> findMenus(Set<String> permissions) {
        List<ResourcePeer> allResources = findAll();
        List<ResourcePeer> menus = new ArrayList<ResourcePeer>();
        for(ResourcePeer resource : allResources) {
            if(resource.isRootNode()) {
                continue;
            }
            if(resource.getType() != ResourcePeer.ResourceType.menu) {
                continue;
            }
            if(!hasPermission(permissions, resource)) {
                continue;
            }
            menus.add(resource);
        }
        return menus;
    }

    private boolean hasPermission(Set<String> permissions, ResourcePeer resource) {
        if(StringUtils.isEmpty(resource.getPermission())) {
            return true;
        }
        for(String permission : permissions) {
            WildcardPermission p1 = new WildcardPermission(permission);
            WildcardPermission p2 = new WildcardPermission(resource.getPermission());
            if(p1.implies(p2) || p2.implies(p1)) {
                return true;
            }
        }
        return false;
    }
}
